﻿using HslCommunication;
using HslCommunication.ModBus;

namespace DataManageSystem.Services.mdc
{
    public class ModbusMdcServices
    {
        private ModbusTcpNet _modbusTcp;
        public ModbusMdcServices(string ipAddress, int port = 502)
        {
            _modbusTcp = new ModbusTcpNet(ipAddress, port);
        }

        public OperateResult Connect()
        {
            // ModbusTcpNet 是无连接的，一般不需要手动连接
            // 但可以测试连接性
            var result = _modbusTcp.ReadUInt16("0");
            return result;
        }

        public ushort[] ReadHoldingRegisters(ushort startAddress, ushort length, byte station = 1)
        {
            _modbusTcp.Station = station;
            var result = _modbusTcp.ReadUInt16(startAddress.ToString(), length);
            if (result.IsSuccess)
            {
                return result.Content;
            }
            else
            {
                Console.WriteLine($"读取失败：{result.Message}");
                return null;
            }
        }


    }
}
